package com.example.dwr.reverseajax;

import com.example.dwr.people.Person;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import org.directwebremoting.Browser;
import org.directwebremoting.ScriptSession;
import org.directwebremoting.ScriptSessionFilter;
import org.directwebremoting.ServerContext;
import org.directwebremoting.ServerContextFactory;
import org.directwebremoting.WebContext;
import org.directwebremoting.WebContextFactory;
import org.directwebremoting.impl.DaemonThreadFactory;
import org.directwebremoting.ui.dwr.Util;

public class PeopleTable
  implements Runnable
{
  private static final String SCRIPT_SESSION_ATTR = "SCRIPT_SESSION_ATTR";

  public PeopleTable()
  {
    ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1, new DaemonThreadFactory());
    executor.scheduleAtFixedRate(this, 1L, 10L, TimeUnit.SECONDS);
  }

  public void run()
  {
    updateTableDisplay();
  }

  public void updateTableDisplay()
  {
    String page = ServerContextFactory.get().getContextPath() + "/reverseajax/peopleTable.html";
    ScriptSessionFilter attributeFilter = new AttributeScriptSessionFilter("SCRIPT_SESSION_ATTR");
    Browser.withPageFiltered(page, attributeFilter, new Runnable()
    {
      public void run()
      {
        Person person = new Person(true);
        String[][] data = { new String[] { person.getId(), person.getName(), person.getAddress(), person.getAge() + "", person.isSuperhero() + "" } };

        Util.addRows("peopleTable", data);
      }
    });
  }

  public void addAttributeToScriptSession() {
    ScriptSession scriptSession = WebContextFactory.get().getScriptSession();
    scriptSession.setAttribute("SCRIPT_SESSION_ATTR", Boolean.valueOf(true));
  }

  public void removeAttributeToScriptSession() {
    ScriptSession scriptSession = WebContextFactory.get().getScriptSession();
    scriptSession.removeAttribute("SCRIPT_SESSION_ATTR");
  }

  protected class AttributeScriptSessionFilter
  implements ScriptSessionFilter {
    private final String attributeName;

    public AttributeScriptSessionFilter(String paramString) {
      this.attributeName = paramString;
    }

    public boolean match(ScriptSession session)
    {
      Object check = session.getAttribute(this.attributeName);
      return ((check != null) && (check.equals(Boolean.TRUE)));
    }
  }
}